<?php
/**
* 第三方登录 wechat
* author:liwenlong0922@163.com
* 
*/ 
class Wechat_auth{
	private $app_data = array();
	function __construct($data=array())
	{
		$this->ci =& get_instance();
		$this->ci->load->model('auth/Users');
		$this->app_data=$data;
	}
	/*
     * 生成微信授权链接
	 * @param string
	 * @return string 
	 */
	function create_url_for_wechat($scope = 'snsapi_userinfo',$redirect_url = 'http://www.hiioo.com/'){
		$state = $this->_rand_state();
		$redirect_url = urlencode($redirect_url);
		$wechat_login_url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->app_data['app_id']
		.'&redirect_uri='.$redirect_url
		.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
		return $wechat_login_url;
	}
    /*
     * 获取微信授权access_token
	 * @param string
	 * @return array 
	 */
	function get_access_token($code) 
	{ 
		$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
		.$this->app_data['app_id'].'&secret='.$this->app_data['app_secret'].'&code='
		.$code.'&grant_type=authorization_code';
		$token = $this->_curl_get_content($token_url);
		return $token; 
	}
    /*
     * 获取用户信息
	 * @param string
	 * @param string
	 * @return array 
	 */	
	function get_user_info($token,$openid) 
	{ 
		$info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token
		.'&openid='.$openid;
		$user = $this->_curl_get_content($info_url);
		return $user; 
	}
	/*
     * 刷新微信授权access_token
	 * @param string
	 * @return array 
	 */
	function refresh_token($token) 
	{ 
		$refresh_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='
		.$this->app_data['app_id'].'grant_type=refresh_token&refresh_token='.$token;
		$token = $this->_curl_get_content($refresh_url);
		return $token; 
	}
	
	function get_user_by_openid($openid)
	{
		$user = $this->ci->users->get_user_by_wechat($openid);
		if(!$user)
			return false;
		/*if($user->wechat_refresh_token){
			$day=7;
			switch($user->wechat_auth_num)
			{
				case '1':
					$day=7;break;
				case '2':
					$day=30;break;
				case '3':
					$day=60;break;
				default:
					$day=90;
			}
			if(time() - strtotime($user->wechat_auth_time) > $day*3600*24){
				//重新要求授权
				return false;
			}else{
				return $this->refresh_token($user->wechat_refresh_token);
			}
		}
		else{
			return false;
		}*/
		$this->ci->session->set_userdata('login_user', array(
            'user_id'	=> $user->id,
            'username'	=> $user->username,
            'email'     => $user->email,
            'mobile'    => $user->mobile,
			'status'	=> STATUS_ACTIVATED,
		));
		return $user;
	}
	
	function get_user_id()
	{
        $user = $this->ci->session->userdata('login_user');
		return $user['user_id'];
	}
	function openid_exists($openid)
	{
		return $this->ci->users->get_user_by_wechat($openid);	
	}
	
	function create_user($data, $password)
	{
		$user = $this->ci->users->get_user_by_wechat($data['openid']);;
		if($user){
			//用户存在的话  更新数据
			$flag = $this->update_user($data,$user);
			return $flag;
		}else{
			$this->ci->load->helper('verify');
			$username = $data['nickname'].rand_pass(4);
			if(!$this->ci->users->is_username_available($username))
				$this->create_user($data,$password);
			$hasher = new PasswordHash(
				$this->ci->config->item('phpass_hash_strength', 'tank_auth'),
				$this->ci->config->item('phpass_hash_portable', 'tank_auth'));
			$hashed_password = $hasher->HashPassword($password);
			$gender = -1;
			switch($data['sex']){
				case '1':
					$gender = 1;
					break;
				case '2':
					$gender = 0;
					break;
				default:
					$gender = -1;
			}
			$user = array(
				'username'				=>  $username,
				'password'				=>  $hashed_password,
				'wechat_id'				=>  $data['openid'],
				'wechat_avatar'			=>	$data['headimgurl'],
				'wechat_refresh_token'	=>	$data['refresh_token'],
				'wechat_auth_time'		=>	date("Y-m-d H:i:s",time()),
				'nickname'				=>	$data['nickname'],
				'gender'				=>	$gender,
				'address'				=>	$data['province'].$data['city'],
				'last_ip'				=>  $this->ci->input->ip_address(),
				'from'					=>	'wechat',
				'wechat_auth_num'		=>	1
			);

			if (!is_null($res = $this->ci->users->create_user($user))) {
					$this->create_autologin($res['user_id']);
					$data['user_id'] = $res['user_id'];
					$data['password'] = $password;
					return $data;
			}
		}
		return NULL;
	}
	
	function update_user($data,$user){
		$temp = true;
		if($user===null){
			$temp = false;
		}
		if(!$this->ci->users->set_auth_num($data,$user,$temp)){
				return false;
		}
		return true;
	}
	private function _curl_get_content($url,$json=true)
	{ 
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 1);
		$result = curl_exec($ch); 
		curl_close($ch); 
		if($json)
			$result = json_decode($result,true); 
		return $result; 
	}
	
	private function _rand_state(){
		$this->ci->load->helper('string');
		$rand = random_string();
		$this->ci->session->set_userdata('wechat_state',$rand);
		$state = md5($rand);
		return $state;
	}
	function get_state()
	{
		return md5($this->ci->session->userdata('wechat_state'));
	}



	
}
